package com.vnp.cooking;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.viewpagerindicator.CirclePageIndicator;
import com.vnp.cooking.UIcontrols.MyCircleImageView;
import com.vnp.cooking.UIcontrols.MyClickAbleImageView;
import com.vnp.cooking.adapter.CanhanListAdapter;
import com.vnp.cooking.adapter.FriendListAdapter;
import com.vnp.cooking.bean.ObjCity;
import com.vnp.cooking.bean.ObjCookpad;
import com.vnp.cooking.fragment.ImageFragmentLogin;
import com.vnp.cooking.fragmentKitchen.CoverCanhan1;
import com.vnp.cooking.fragmentKitchen.CoverCanhan2;
import com.vnp.cooking.fragmentKitchen.CoverUser1;
import com.vnp.cooking.fragmentKitchen.CoverUser2;
import com.vnp.cooking.httpclient.HttpClientHelper;
import com.vnp.cooking.httpclient.MyJsonHttpResponseHandler;
import com.vnp.cooking.utils.HelperListview;
import com.vnp.cooking.utils.PreferenceHelper;
import com.vnp.cooking.utils.Utils;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.YuvImage;
import android.graphics.Bitmap.Config;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class XemThongTinUserActivity extends FragmentActivity implements
		OnClickListener {

	ImageButton btnBack;
	ArrayList<ObjCookpad> objCookpads = new ArrayList<ObjCookpad>();
	ObjCookpad objCookpad = new ObjCookpad();
	// load more activity
	ProgressBar prbLoadActivity;
	ProgressBar progressBarLoadmore;
	Button btnLoadMore;
	View footerMain;
	int mPage = 0;
	FriendListAdapter adapter;
	Handler mHandler = new Handler();
	private static final String SCREEN_LABEL = "Xem thong tin user screen";

	TextView noActivity;

	// ten
	TextView txtFriendName, txtYeuthich, txtDadang;
	ListView listActivity;
	PreferenceHelper preferenceHelper;

	Runnable r = new Runnable() {

		@Override
		public void run() {
			getActivityUser(mPage);
		}
	};
	
	HashMap<Integer, String> mapCity = new HashMap<Integer, String>();
	ArrayList<ObjCity> objCities = new ArrayList<ObjCity>();
	
	// header
	int yeuthich, dadang;
	int isTurn = 0;
	MyClickAbleImageView btnYeuthich, btnDadang;
	MyCircleImageView imageAvatar;
	
//	TextView levelUser, cityUser;
	DisplayImageOptions options = new DisplayImageOptions.Builder()
									.cacheInMemory(false)
									.cacheOnDisc(false)
									.bitmapConfig(Config.RGB_565)
									.build();
	
	View actionbar;
	
	ViewPager pager;
	MyAdapter myFragmentPagerAdapter;
	CirclePageIndicator indicator;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_xem_thong_tin_user);
		preferenceHelper = new PreferenceHelper(this);
		objCookpad = getIntent().getParcelableExtra("objCookpad");
		
		actionbar = (View) findViewById(R.id.actionbar);

		btnBack = (ImageButton) findViewById(R.id.btn_back);
		txtFriendName = (TextView) findViewById(R.id.txt_friend_name);
		listActivity = (ListView) findViewById(R.id.listActivityUser);
		prbLoadActivity = (ProgressBar) findViewById(R.id.prgGetActivity);
		noActivity = (TextView) findViewById(R.id.no_activity);

		getInfoFriend();

		mHandler.post(r);
		addHeader();
		adapter = new FriendListAdapter(XemThongTinUserActivity.this,
				objCookpads);
		listActivity.setAdapter(adapter);
		loadCacheDataCity();
		
		setFont();
		init();
		ApplicationContext.getGaTracker().set(Fields.SCREEN_NAME, SCREEN_LABEL);

	}
	
	@Override
	public void onStart() {
		super.onStart();
		ApplicationContext.getGaTracker().send(MapBuilder.createAppView().build());
	}

	@Override
	public void onStop() {
		super.onStop();
	}
	
	private void setFont() {
		txtFriendName.setTypeface(Utils.getTypefaceRegular(XemThongTinUserActivity.this), Typeface.BOLD);
	}
	
	private void setFontHeader() {
		txtDadang.setTypeface(Utils.getTypefaceRegular(XemThongTinUserActivity.this));
		txtYeuthich.setTypeface(Utils.getTypefaceRegular(XemThongTinUserActivity.this));
	}
	
	void init() {
		btnBack.setOnClickListener(this);
		txtFriendName.setText(objCookpad.getNamePersonCookpad());
		actionbar.setOnClickListener(this);
		addFooterView();
	}
	
	
	void loadCacheDataCity() {
		String cache = preferenceHelper.getDataFilter();
		if(!cache.equals("")) {
			try {
				JSONObject response = new JSONObject(cache);
				parseData(response);
			} catch (Exception e) { }
		}
	}
	
	public void parseData(JSONObject re) {
		try {
			int status = re.getInt("status");
			if (status == 200) {
				JSONObject data = re.getJSONObject("data");
				JSONArray cities = data.getJSONArray("city");
				for (int i = 0; i < cities.length(); i++) {
					JSONObject city = cities.getJSONObject(i);
					ObjCity objCity = new ObjCity();
					objCity.setId(city.getInt("id"));
					objCity.setName(city.getString("name"));
					objCities.add(objCity);
					
					int key = city.getInt("id");
					String value = city.getString("name");
					mapCity.put(key, value);
				}
			} else {
				Toast.makeText(XemThongTinUserActivity.this, "Không lấy được dữ liệu",  Toast.LENGTH_SHORT).show();
			}
		} catch (JSONException e) {
			e.printStackTrace();
			Toast.makeText(XemThongTinUserActivity.this, "Không lấy được dữ liệu",  Toast.LENGTH_SHORT).show();
		}
	}

	

	void addHeader() {
		LayoutInflater inflater = getLayoutInflater();
		ViewGroup header = (ViewGroup) inflater.inflate(R.layout.header_acivity_user, listActivity, false);
		btnYeuthich = (MyClickAbleImageView) header.findViewById(R.id.btn_dathich);
		btnDadang = (MyClickAbleImageView) header.findViewById(R.id.btn_dadang);
		txtYeuthich = (TextView) header.findViewById(R.id.txt_yeuthich);
		txtDadang = (TextView) header.findViewById(R.id.txt_dadang);
		indicator = (CirclePageIndicator) header.findViewById(R.id.indicator);
		
		pager = (ViewPager) header.findViewById(R.id.viewpager);
		
		setFontHeader();
		
		btnYeuthich.setOnClickListener(this);
		btnDadang.setOnClickListener(this);
		listActivity.addHeaderView(header, null, false);
	}
	
	
	// xu li phan cover slide
	public static class MyAdapter extends FragmentPagerAdapter {
		public MyAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public int getCount() {
			return 2;
		}

		@Override
		public Fragment getItem(int position) {
			switch (position) {
			case 0:
				return new CoverUser1();
			case 1:
				return new CoverUser2();
			default:
				return null;
			}
		}
	}
	
	

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.actionbar:
			listActivity.smoothScrollToPosition(0);
			break;
		case R.id.btn_back:
			closeActivity();
			break;
		case R.id.btn_dathich:
			Intent c = new Intent(this, CongthucDaThichActivity.class);
			c.putExtra("userID", objCookpad.getIdNamePerson());
			startActivity(c);
			overridePendingTransition(R.anim.open_next, R.anim.close_main);
			break;
		case R.id.btn_dadang:
			Intent a = new Intent(this, CongthucDadangActivity.class);
			a.putExtra("userID", objCookpad.getIdNamePerson());
			startActivity(a);
			overridePendingTransition(R.anim.open_next, R.anim.close_main);
			break;
		case R.id.btn_load_more:
			mPage = mPage + 1;
			getActivityUser(mPage);
			progressBarLoadmore.setVisibility(View.VISIBLE);
			btnLoadMore.setText("Đang lấy thêm công thức...");
			break;
		default:
			break;
		}
	}

	void getActivityUser(int page) {
		HttpClientHelper httpClientHelper = new HttpClientHelper(
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						super.onFailure(error);
						prbLoadActivity.setVisibility(View.GONE);
						btnLoadMore.setText("Lấy thêm công thức");
						progressBarLoadmore.setVisibility(View.GONE);
					}

					@Override
					public void onSuccess(JSONObject re) {
						prbLoadActivity.setVisibility(View.GONE);
						Log.i("DATA", "Nhay vao sucess");
						try {
							int status = re.getInt("status");
							if (status == 200) {
								JSONArray data = re.getJSONArray("data");
								isTurn = isTurn + 1;
								btnLoadMore.setText("Lấy thêm công thức");
								progressBarLoadmore.setVisibility(View.GONE);
								Log.i("DATA", "ACIVITY: " + data.toString());
								if (data.length() == 0) {
									footerMain.setVisibility(View.GONE);
									progressBarLoadmore
											.setVisibility(View.GONE);
									noActivity.setVisibility(View.VISIBLE);
									return;
								}
								if (data.length() < 11) {
									footerMain.setVisibility(View.GONE);
									progressBarLoadmore
											.setVisibility(View.GONE);
								}
								for (int i = 0; i < data.length(); i++) {
									JSONObject jo = data.getJSONObject(i);
									JSONObject tacgia = jo
											.getJSONObject("author");

									ObjCookpad objCookpad = new ObjCookpad();
									objCookpad.setId(jo.getString("id"));
									objCookpad.setIdNamePerson(tacgia
											.getString("id"));
									objCookpad.setNamePersonCookpad(tacgia
											.getString("name"));
									objCookpad.setDescriptionCookpad(jo
											.getString("desc"));
									objCookpad.setNameCookpad(jo
											.getString("name"));

									JSONObject images = jo
											.getJSONObject("image");
									objCookpad.setUrlImageCookpad(images
											.getString("cover"));

									objCookpad.setThoigianNauan(jo
											.getString("time"));
									objCookpad.setCreatedDateCookpad(jo
											.getString("created"));
									objCookpad.setAction(jo.getString("action"));
									objCookpad.setViewedCookpad(jo
											.getInt("view_count"));
									objCookpad.setLikeCookpad(jo
											.getInt("like_count"));
									objCookpad.setUrlAvatar(preferenceHelper.getFriendUrlAvatar());
									objCookpads.add(objCookpad);

								}
								adapter.notifyDataSetChanged();
								txtYeuthich.setText("Yêu thích (" + ""
										+ yeuthich + ")");
								txtDadang.setText("Đã đăng (" + "" + dadang
										+ ")");
								if (data.length() < 10) {
									footerMain.setVisibility(View.GONE);
								} else {
									footerMain.setVisibility(View.VISIBLE);
								}
							} else {
								prbLoadActivity.setVisibility(View.GONE);
								btnLoadMore.setText("Lấy thêm công thức");
								progressBarLoadmore.setVisibility(View.GONE);
							}

						} catch (JSONException e) {
							e.printStackTrace();
							prbLoadActivity.setVisibility(View.GONE);
							btnLoadMore.setText("Lấy thêm công thức");
							progressBarLoadmore.setVisibility(View.GONE);
						}
					}
				});
		httpClientHelper.getInfoActivity(objCookpad.getIdNamePerson(), page);

	}

	void getInfoFriend() {
		HttpClientHelper httpClientHelper = new HttpClientHelper(
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						super.onFailure(error);
					}

					@Override
					public void onSuccess(JSONObject re) {
						try {
							int status = re.getInt("status");
							if (status == 200) {
								JSONObject data = re.getJSONObject("data");

								Log.i("DATA",
										"Thong tin USER: " + data.toString());

								String name = data.getString("name");
								String levelName = data.getString("level_name");
								String about = data.getString("about");
								int cityID = data.getInt("city_id");
								String avatar = data.getString("avatar");
								yeuthich = data.getInt("total_favourite");
								dadang = data.getInt("total_created");
								
								// hien thi thanh pho
								Iterator myVeryOwnIterator = mapCity.keySet().iterator();
								while(myVeryOwnIterator.hasNext()) {
								    int key= (Integer) myVeryOwnIterator.next();
								    
								    String value=(String)mapCity.get(key);
								    Log.i("DATA", "Key: "+key+ "Value: "+value);
								    if (key == cityID) {
								    	preferenceHelper.setFriendCityName(value);
								    }
								}
								
								
								
								preferenceHelper.setFriendName(name);
								preferenceHelper.setFriendURLAvatar(avatar);
								Log.i("DATA", "AVATAR :" + preferenceHelper.getFriendUrlAvatar());
								preferenceHelper.setFriendLevelName(levelName);
								preferenceHelper.setFriendAbout(about);
								adapter.notifyDataSetChanged();
								
								
								
								myFragmentPagerAdapter = new MyAdapter(getSupportFragmentManager());
								pager.setAdapter(myFragmentPagerAdapter);
								indicator.setViewPager(pager);
							} else {

							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

				});
		httpClientHelper.getInfoUser(objCookpad.getIdNamePerson());
	}

	void addFooterView() {
		View loadMoreView = ((LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
				R.layout.footer_loadmore, null, false);
		footerMain = (View) loadMoreView.findViewById(R.id.footer_main);
		footerMain.setVisibility(View.GONE);
		listActivity.addFooterView(loadMoreView);
		btnLoadMore = (Button) loadMoreView.findViewById(R.id.btn_load_more);
		progressBarLoadmore = (ProgressBar) loadMoreView
				.findViewById(R.id.progressBar1);
		btnLoadMore.setOnClickListener(this);
	}

	void closeActivity() {
//		preferenceHelper.setFriendURLAvatar("");
		finish();
		overridePendingTransition(R.anim.open_main, R.anim.close_next);
	}

	@Override
	public void onBackPressed() {
		closeActivity();
	}

}
